package cn.stylefeng.guns.modular.api.service;


import cn.stylefeng.guns.modular.api.model.result.TaskResult;
import cn.stylefeng.guns.modular.api.vo.TemplateData;
import cn.stylefeng.guns.modular.api.vo.WxMssVo;
import cn.stylefeng.guns.sys.core.exception.enums.BizExceptionEnum;
import cn.stylefeng.guns.sys.modular.system.entity.User;
import cn.stylefeng.guns.sys.modular.system.service.UserService;
import cn.stylefeng.roses.kernel.model.exception.ServiceException;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;

import lombok.Data;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.client.RestTemplate;

import javax.annotation.PostConstruct;

/**
 * Created by qcl on 2018/9/11.
 * 微信小程序推送服务，
 * 包含获取access_token的服务
 */
@Service
@Slf4j
public class WxPushServiceQcl {

    private RestTemplate restTemplate;

    @PostConstruct
    public void init() {
        restTemplate = new RestTemplate();
    }

    @Autowired
    private UserService userService;

    /*
     * 微信小程序推送单个用户
     * */
    public String pushOneUser(String formid, TaskResult taskResult) {

        try {
            //获取access_token
            String access_token = getAccess_token("wxf9435af1423cfbe5", "50ed46f2b5a62cc1df3b5df27d687572");
            String url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send" +
                    "?access_token=" + access_token;

            log.info("小程序accessToken" + url);
            //获取openId

            String account = taskResult.getWorker().split("-")[0];
            String code = "";
            if (account != null) {
                User user = userService.getByAccount(account);
                code = user.getWxcode();
            }
            String openid = getOpenId("wxf9435af1423cfbe5", "50ed46f2b5a62cc1df3b5df27d687572", code);
            //拼接推送的模版
            WxMssVo wxMssVo = new WxMssVo();
            wxMssVo.setTouser(openid);//用户openid
            wxMssVo.setAccess_token(access_token);//用户openid
            wxMssVo.setTemplate_id("_ifg4bruhbNlpX4_QLab5tsh5MQPVN7xjgLO5BkM2uo");//模版id
            wxMssVo.setForm_id(formid);//formid


            Map<String, TemplateData> m = new HashMap<>(5);

            // title：名字，
            // worker：执行人，
            // status: 状态

            TemplateData keyword2 = new TemplateData();
            keyword2.setValue(taskResult.getTitle());
            m.put("thing3", keyword2);
            wxMssVo.setData(m);

            TemplateData keyword3 = new TemplateData();
            keyword3.setValue(taskResult.getWorker());
            m.put("name5", keyword3);
            wxMssVo.setData(m);

            TemplateData keyword6 = new TemplateData();
            String statusString = "未执行";
            if (taskResult.getType() == 1) {
                statusString = "已执行";
            } else if (taskResult.getType() == 2) {
                statusString = "执行取消";
            }
            keyword6.setValue(statusString);
            m.put("phrase12", keyword6);
            wxMssVo.setData(m);

            ResponseEntity<String> responseEntity =
                    restTemplate.postForEntity(url, wxMssVo, String.class);
            log.error("小程序推送结果={}", responseEntity.getBody());
            return responseEntity.getBody();
        }catch (Exception e) {
            throw new ServiceException(500,"推送结果失败");
        }



    }

    /*
     * 获取access_token
     * appid和appsecret到小程序后台获取，当然也可以让小程序开发人员给你传过来
     * */
    public String getAccess_token(String appid, String appsecret) {
        //获取access_token
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential" +
                "&appid=" + appid + "&secret=" + appsecret;
        String json = restTemplate.getForObject(url, String.class);
        AccessToken accessToken = new Gson().fromJson(json, AccessToken.class);
        return accessToken.getAccess_token();
    }

    /*
     * 获取access_token
     * appid和appsecret到小程序后台获取，当然也可以让小程序开发人员给你传过来
     * */
    public String getOpenId(String appid, String appsecret, String code) {
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" +
                appid + "&secret=" + appsecret + "&js_code=" + code + "&grant_type=authorization_code";
        Map<String, String> result = new HashMap<String, String>();
        try {
            String ret = restTemplate.getForObject(url, String.class);
            System.out.println(ret);
            JSONObject obj = JSONObject.parseObject(ret);
            String openid = obj.getString("openid");
            result.put("openid", openid);

        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        return result.get("openid");


    }

    @Data
    private class AccessToken {
        private String access_token;
    }
}